<template>
  <div class="waterfall" ref="waterfall">
    <slot></slot>
    <div class="waterfall-loading" ref="loading" v-show="isLoading">
      <i class="el-icon-loading"></i>
    </div>
  </div>
</template>

<script>
import throttle from "@/utils/throttle.js"; // 节流函数
export default {
  name: "waterfall",

  props: ["isLoading"],

  /* 监听是否请求新数据 */
  mounted() {
    this.handler = throttle(this.scrollHandler.bind(this), 200); // 绑定 this 为当前实例
    window.addEventListener("scroll", this.handler);
  },

  destroyed() {
    window.removeEventListener("scroll", this.handler);
  },

  methods: {
    scrollHandler() {
      if (this.isLoading) return; // this 为当前实例
      if (
        this.$refs.waterfall.getBoundingClientRect().bottom <
        document.documentElement.clientHeight
      ) {
        // console.log("上拉加载");
        this.$emit("loadMore"); // 向父组件传递
      }
    },
  },
};
</script>

<style>
.waterfall-loading {
  width: 100%;
  height: 20px;
  text-align: center;
}
</style>